package menuService

import (
	"fmt"
	menuDto "news_for_deepseek_interface/dto/admin/system/menu"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"
	"time"
)

func UpdateMenu(params menuDto.UpdateMenuRequest) (err error) {
	db := model.GetInstance().GetDB()

	level := 0
	if params.ParentId != 0 {
		var parentMenu adminModel.AdminAuthRuleStruct
		if err = db.Where("id = ?", params.ParentId).First(&parentMenu).Error; err != nil {
			return fmt.Errorf("父级菜单不存在")
		}
		level = parentMenu.Level + 1
	}

	result := db.
		Model(&adminModel.AdminAuthRuleStruct{}).
		Where("id = ?", params.Id).
		Updates(map[string]interface{}{
			"parent_id":   params.ParentId,
			"level":       level,
			"path":        params.Path,
			"name":        params.Name,
			"component":   params.Component,
			"title":       params.Title,
			"show_parent": params.ShowParent,
			"icon":        params.Icon,
			"rank":        params.Rank,
			"show_link":   params.ShowLink,
			"updated_at":  time.Now().Format("2006-01-02 15:04:05"),
		})

	if result.Error != nil {
		return fmt.Errorf("更新菜单失败: %v", result.Error)
	}

	if result.RowsAffected == 0 {
		return fmt.Errorf("菜单不存在")
	}

	return nil
}
